package com.yanchi.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author yanchi
 * @date 2022/1/21 14:24
 */
@RestController
public class DemoController {

    @SentinelResource(value = "test", blockHandler = "blockHandler",defaultFallback = "fall")   // 定义控制资源以及如何配置控制策略
    @GetMapping("demo")
    public String demo(Integer id){
        if (id < 0){
            throw new RuntimeException("id不合法");
        }
        return "demo ok !!!";
    }

    /**
     * 服务限流的方法
     * @param id
     * @param e
     * @return
     */
    public String blockHandler(Integer id, BlockException e){
        if (e instanceof FlowException){
            return "FlowException";
        }else if (e instanceof ParamFlowException){
            return "ParamFlowException";
        }else if (e instanceof DegradeException){
            return "DegradeException";
        }else if (e instanceof AuthorityException){
            return "AuthorityException";
        }else if (e instanceof SystemBlockException){
            return "SystemBlockException";
        }else {
            return "服务被限流";
        }
    }
    /**
     * 业务代码出异常默认的降级方法
     * @return
     */
    public String fall(){
        return "服务器出错了";
    }


}
